package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.itheima.entity.Result;
import com.itheima.mapper.MemberMapper;
import com.itheima.mapper.OrderMapper;
import com.itheima.mapper.OrderSettingMapper;
import com.itheima.pojo.Member;
import com.itheima.pojo.Order;
import com.itheima.pojo.OrderInfo;
import com.itheima.pojo.OrderSetting;
import com.itheima.service.OrderService;
import com.itheima.utils.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import static com.itheima.constant.MessageConstant.*;

@Service(version = "1.0", interfaceClass = OrderService.class)
@Transactional
public class OrderServiceImpl implements OrderService {

    @Autowired
    JedisPool jedisPool;
    @Resource
    OrderSettingMapper orderSettingMapper;
    @Resource
    MemberMapper memberMapper;
    @Resource
    OrderMapper orderMapper;

    @Override
    public Result send(String telephone) {
        /**
         * 发验证码 验证码  telephone
         * 验证码存在redis中, 设置过期时间
         */
//        int code = RandomUtils.nextInt(100000, 999999);
        int code = 123456;
//        boolean flag = SmsUtil.sendSms(telephone, code);
        System.out.println("发短信手机号:" + telephone + "   " + "验证码:" + code);
        boolean flag = true;
        if (flag) {
            Jedis jedis = jedisPool.getResource();
            jedis.setex("ORDER_" + telephone, 300, String.valueOf(code));
            if (jedis != null) {
                jedis.close();
            }
            return Result.success(SEND_VALIDATECODE_SUCCESS, null);
        }
        return Result.fail(SEND_VALIDATECODE_FAIL);
    }

    @Override
    public Result submit(OrderInfo orderInfo) {
        //校验验证码
        Jedis jedis = null;
        try {
            String validateCode = orderInfo.getValidateCode();
            jedis = jedisPool.getResource();
            String code = jedis.get("ORDER_" + orderInfo.getTelephone());
            if (code == null || !code.equals(validateCode)) {
                return Result.fail(VALIDATECODE_ERROR);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        //1、检查用户所选择的预约日期是否已经提前进行了预约设置，如果没有设置则无法进行预约
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date date = null;
        try {
            date = simpleDateFormat.parse(orderInfo.getOrderDate());
        } catch (ParseException e) {
            e.printStackTrace();
            return Result.fail(SYSTEM_MESSAGE_FAIL);
        }
        OrderSetting orderSetting = orderSettingMapper.findOrderSettingByDate(date);
        if (orderSetting == null) {
            return Result.fail(SELECTED_DATE_CANNOT_ORDER);
        }
        //2、检查用户所选择的预约日期是否已经约满，如果已经约满则无法预约
        //设置的预约数
        Integer number = orderSetting.getNumber();
        //已预约数
        Integer reservations = orderSetting.getReservations();
        if (reservations >= number) {
            return Result.fail(ORDER_FULL);
        }
        //3、检查用户是否重复预约（同一个用户在同一天预约了同一个套餐），如果是重复预约则无法完成再次预约
        Date orderDate = orderSetting.getOrderDate();
        Integer setMealId = orderInfo.getSetMealId();
        String telephone = orderInfo.getTelephone();
        //通过手机号查询用户
        //检查用户是否重复预约
        Member member = memberMapper.findMemberByPhone(telephone);
        if (member != null) {
            Integer memberId = member.getId();
            Order order = orderMapper.findOrder(memberId, orderDate, setMealId);
            if (order != null) {
                return Result.fail(HAS_ORDERED);
            }
        }
        //4、检查当前用户是否为会员，如果是会员则直接完成预约，如果不是会员则自动完成注册并进行预约
        if (member == null) {
            member = new Member();
            member.setPhoneNumber(telephone);
            member.setIdCard(orderInfo.getIdCard());
            member.setName(orderInfo.getName());
            member.setSex(orderInfo.getSex());
            member.setRegTime(new Date());
            this.memberMapper.save(member);
        }

        Order order = new Order();
        order.setOrderType(Order.ORDERTYPE_WEIXIN);
        order.setOrderStatus(Order.ORDERSTATUS_NO);
        order.setOrderDate(orderDate);
        order.setSetmealId(setMealId);
        order.setMemberId(member.getId());
        orderMapper.save(order);

        //5、预约成功，更新当日的已预约人数
        orderSettingMapper.updateReservations(orderSetting.getId());
        return Result.success(ORDER_SUCCESS, order.getId());
    }

    @Override
    public Result findById(Integer id) {
        try {
            Map<String, Object> map = orderMapper.findById(id);
            Date orderDate = (Date) map.get("orderDate");
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
            String date = simpleDateFormat.format(orderDate);
            map.put("orderDate", date);
            return Result.success(QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return Result.fail(QUERY_ORDER_FAIL);
    }
}
